﻿namespace SuperMarieApi.App.Controllers.Framework.Config
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Xml;

    using SuperMarieApi.App.Controllers.Framework.Config.ConfigFile;
    using SuperMarieApi.App.Controllers.Framework.Config.DataAccess;
    using SuperMarieApi.App.Controllers.Framework.Config.Logging;

    public static class ConfigManager
    {
        public static DataAccessConfig DataAccessConfig { get; private set; }
        public static LoggingConfig LoggingConfig { get; private set; }
        private static readonly XmlConfigProvider _xmlConfigProvider;
        private static readonly XmlCachedConfigProvider _xmlCachedConfigProvider;

        static ConfigManager()
        {
            DataAccessConfig = ConfigurationManager.GetSection("dataAccess") as DataAccessConfig;
            LoggingConfig = ConfigurationManager.GetSection("logging") as LoggingConfig;
            _xmlConfigProvider = new XmlConfigProvider();
            _xmlCachedConfigProvider = new XmlCachedConfigProvider();
        }

        public static T GetXmlConfig<T>() where T:class,new()
        {
            return _xmlConfigProvider.GetConfig<T>();
        }

        public static T GetXmlCachedConfig<T>() where T : class,new()
        {
            return _xmlCachedConfigProvider.GetConfig<T>();
        }

        private static Dictionary<string, List<KeyValuePair<string, string>>> _kvCache;
        public static List<KeyValuePair<string, string>> GetKeyValuePair(string name)
        {
            if (_kvCache == null)
            {
                _kvCache = new Dictionary<string, List<KeyValuePair<string, string>>>();
                string file = AppDomain.CurrentDomain.BaseDirectory + "Configs\\KeyValuePair.xml";

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(file);
                var nodes = xmlDoc.SelectNodes("/Root/KeyValuePair");
                KeyValuePair<string, string> kv;
                foreach (XmlNode n in nodes)
                {
                    var items = n.SelectNodes("item");
                    string key = n.Attributes["name"].Value;
                    if (!_kvCache.ContainsKey(key))
                    {
                        List<KeyValuePair<string, string>> kvList = new List<KeyValuePair<string, string>>();
                        foreach (XmlNode i in items)
                        {
                            kv = new KeyValuePair<string, string>(i.Attributes["key"].Value
                                , i.Attributes["value"].Value);
                            kvList.Add(kv);
                        }
                        _kvCache.Add(key, kvList);
                    }
                }
            }

            if (_kvCache.ContainsKey(name))
            {
                return _kvCache[name];
            }

            return new List<KeyValuePair<string, string>>();
        }
    }
}
